<template>
  <div>
    <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片区域 -->
      <el-card>
        <el-row>
          <el-col>
            <el-button type="primary" @click="showAddDialog('add')">添加分类</el-button>
          </el-col>
        </el-row>

        <!-- 表格区域 -->
        <el-table
          :data="cateList"
          row-key="cat_id"
          border
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column
            prop="cat_name"
            label="分类名称"
            sortable>
          </el-table-column>
          <el-table-column
            prop="cat_deleted"
            label="是否有效"
            sortable>
            <template slot-scope="scope">
              <i :class="[scope.row.cat_deleted ? 'el-icon-error' : 'el-icon-success']" style="color:lightgreen;"></i>
            </template>
          </el-table-column>
          <el-table-column
            prop="cat_level"
            label="级别">
          </el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" @click="showAddDialog('edit',scope.row.cat_id)" size="mini"></el-button>
              <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row.cat_id)" size="mini"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClosed">

      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
        <el-form-item label="父级分类" >
           <el-cascader
          v-model="selectedKeys"
          :options="parentCateList"
          :props="cascaderProps" clearable
          @change="parentCateChange" style="width:100%">
          </el-cascader>
        </el-form-item>
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>

      </el-form>

      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],

      // 查询信息
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总数据条数
      total: 0,
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加商品分类的保存数据
      addForm: {
        cat_id: 0,
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 控制添加对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑商品分类的保存数据
      editForm: {
        cat_id: '',
        cat_name: '',
        cat_pid: '',
        cat_level: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        cat_name: [{
          required: true,
          message: '请输入分类名称',
          trigger: 'blur'
        }, {
          min: 4,
          message: '分类名称的长度大于4 个字符',
          trigger: 'blur'
        }]
      },
      // 父级分类列表
      parentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 选中的父级分类id数组
      selectedKeys: [],
      // 对话框的title
      dialogTitle: '添加分类',
      opt: 'add'
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },

    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },

    // 监听页码值改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
      this.$refs.addFormRef.resetFields()
    },

    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败!')
      }
      this.parentCateList = res.data
    },

    // 显示添加分类的对话框
    async showAddDialog (opt, id) {
      this.opt = opt

      this.getParentCateList()
      if (opt === 'edit') {
        this.dialogTitle = '编辑分类'
        const { data: res } = await this.$http.get(`categories/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('获取分类失败！')
        }
        this.addForm = res.data
        this.selectedKeys = res.data.cat_pid
      } else if (opt === 'add') {
        this.dialogTitle = '添加分类'
      } else {
        return
      }
      this.addDialogVisible = true
    },

    // 添加分类
    async addCate () {
      if (this.opt === 'add') {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          console.info(this.addForm)
          const param = {
            cat_pid: this.addForm.cat_pid,
            cat_name: this.addForm.cat_name,
            cat_level: this.addForm.cat_level
          }
          debugger
          const { data: res } = await this.$http.post('categories', param)
          if (res.meta.status !== 201) {
            return this.$message.error('添加分类失败!')
          }

          this.$message.success('添加分类成功!')
          debugger
          this.addDialogVisible = false
          this.getCateList()
        })
      } else if (this.opt === 'edit') {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.put(
            'categories/' + this.addForm.cat_id,
            this.addForm)
          if (res.meta.status !== 200) {
            return this.$message.error('编辑分类失败!')
          }

          this.$message.success('编辑分类成功!')
          this.addDialogVisible = false
          this.getCateList()
        })
      }
    },

    // 父级分类选择项发生变化
    parentCateChange () {
      // 如果selectedKeys的length大于0，则选中了父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的id
        this.addForm.cat_pid =
        this.selectedKeys[this.selectedKeys.length - 1]

        // 当前分类的等级
        this.addForm.cat_level =
        this.selectedKeys.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },

    // 显示编辑对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 删除商品分类
    async deleteCate (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除!')
      }
      const { data: res } = await this.$http.delete(`categories/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败!')
      }
      this.$message.success('删除分类成功!')
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
